package booksys.bob;

import booksys.common.CurrentUser;
import booksys.common.Utils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;

import java.util.*;

public class BobService {

    public Map<String, Object> getBobcardList(String userID, QueryDto queryDto) {
        queryDto.setMa_id(userID);
        SqlSession sess = Utils.openSession();
        try {
            BobDao dao = sess.getMapper(BobDao.class);

            //执行映射器方法之前执行分页参数(页码，每页记录数)设置
            PageHelper.startPage(queryDto);


            List<Bobcard> bobList = dao.findBobcardList(queryDto);


            //执行映射器方法之后，立即执行PageInfo对象创建
            PageInfo<Bobcard> pageInfo = new PageInfo<Bobcard>(bobList);

            Map<String,Object> page = new HashMap<>();
            page.put("current",pageInfo.getPageNum());//当前页
            page.put("pageSize",pageInfo.getPageSize());//每页最大记录数
            page.put("total",pageInfo.getTotal());//总记录数
            page.put("pages",pageInfo.getPages());//总页数
            page.put("size",pageInfo.getSize());//当前页记录数
            page.put("list",pageInfo.getList());//当前页数据记录
            page.put("first",1);
            page.put("pre",pageInfo.getPrePage());
            page.put("next",pageInfo.getNextPage());
            page.put("last",pageInfo.getPages());


            sess.commit();

            return page;

        } catch (Exception e) {
            sess.rollback();
            throw new RuntimeException("加载借阅卡信息失败！", e);
        } finally {
            sess.close();
        }
    }

    public void addBobcard(BobcardDto dto, String userId) {
        dto.setMa_id(userId);

        SqlSession sess = Utils.openSession();
        try {
            BobDao dao = sess.getMapper(BobDao.class);

            boolean hasstudent = dao.findstudent(dto.getSt_id());
            if (!hasstudent) {
                throw new RuntimeException("学号输入错误！学生表中查无此人");
            }

            boolean hasbook = dao.findbook(dto.getBb_id());
            if (!hasbook) {
                throw new RuntimeException("书号输入错误！书库中无此书");
            }

            boolean bookbeborrow = dao.findbookbeborrow(dto.getBb_id());
            if (bookbeborrow) {
                throw new RuntimeException("该书已被借出！请修改以前借阅卡或者新增借阅卡书号");
            }

            java.util.Calendar cal = java.util.Calendar.getInstance();

            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH) + 1;

            String mom = month < 10 ? ("0" + month) : ("" + month);

            String newNum = dao.findBobcardNewNum(year + mom);

            dto.setBob_id(year + mom + newNum);
            dto.setBb_btime(cal.getTime());
            cal.add(Calendar.DATE, 7);
            dto.setBb_extime(cal.getTime());

            dao.insertBobcard(dto);
            dao.updatebb_stateto1(dto);

            sess.commit();

        } catch (Exception e) {
            sess.rollback();
            if (e instanceof RuntimeException) {
                throw e;
            }
            throw new RuntimeException("新增借阅卡失败！", e);


        } finally {
            sess.close();
        }
    }

    public void updBobcard(BobcardDto dto) {
        SqlSession sess = Utils.openSession();
        try {
            BobDao dao = sess.getMapper(BobDao.class);

            boolean hasstudent = dao.findstudent(dto.getSt_id());
            if (!hasstudent) {
                throw new RuntimeException("学号输入错误！学生表中查无此人");
            }

            boolean hasbook = dao.findbook(dto.getBb_id());
            if (!hasbook) {
                throw new RuntimeException("书号输入错误！书库中无此书");
            }

            if (!dao.getbb_id(dto.getBob_id()).equals(dto.getBb_id())) {
                boolean bookbeborrow = dao.findbookbeborrow(dto.getBb_id());
                if (bookbeborrow) {
                    throw new RuntimeException("该书已被借出！请修改以前借阅卡或者新增借阅卡书号");
                }
            }

            if (dao.getbb_retime(dto) != null) {
                if (dto.getBb_retime().before(dto.getBb_btime())) {
                    throw new RuntimeException("实际归还日期设置错误！请重新设置！");
                }
            }


            if(dto.getBb_retime() != null && dao.getbb_retime(dto) == null) {
                dao.updatebb_stateto0(dto);
                dao.updateBobcard(dto);
            }else {
                dao.updatebb_stateto0(dto);
                dao.updateBobcard(dto);
                dao.updatebb_stateto1(dto);
            }

            sess.commit();

        } catch (Exception e) {
            sess.rollback();
            if (e instanceof RuntimeException) {
                throw e;
            }
            throw new RuntimeException("修改借阅卡信息失败！", e);
        } finally {
            sess.close();
        }
    }

    public void delBobcard(BobcardDto dto) {
        SqlSession sess = Utils.openSession();
        try {
            BobDao dao = sess.getMapper(BobDao.class);

            if(dao.getbb_retime(dto) == null){
                throw new RuntimeException("图书未归还，禁止删除");
            }

            dao.updatebb_stateto0(dto);
            dao.deleteBobcard(dto.getBob_id());
            sess.commit();
        } catch (Exception e) {
            sess.rollback();
            if (e instanceof RuntimeException) {
                throw e;
            }
            throw new RuntimeException("删除借阅卡失败!", e);
        } finally {
            sess.close();
        }
    }
}
